<?php  
namespace Home\Controller;
use Think\Controller;

class MsProductsController extends CommonController
{
  protected $this_table = "products";

  public function __construct()
  {
    parent::__construct();
  }

  public function _before_create()
  {
    $this->auth_validate('create', true);
    $this->shops_close();
  }

  public function _before_update()
  {
   $this->auth_validate('update', true);
   $this->shops_close();
  }

  public function _before_show()
  {
    $this->auth_validate('show');
  }

  public function _before_index()
  {
    $this->auth_validate('index');
  }

  public function _before_delete()
  {
    $this->auth_validate('delete');
    $this->shops_close();
  }
  /**
   * [增/删/改权限检查]
   * @return [type] [description]
   */
  private function auth_validate($action, $is_business = false)
  {
    $this->check_login();

    //是否商户用户
    if (empty($this->shop_id) && $this->types != 1 && $is_business) {
      return_data("error", "$action.{$this->this_table}.deny");
    }
  }

  /**
   * [添加商品]
   * @return [type] [description]
   */
  public function create()
  {
    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);
    //  $data = [];
    // $data['name'] = '1123';
    // $data['logo'] = '1111';
    // $data['price'] = '1111111';
    // $data['product_num'] = '1111';
    // $data['original_price'] = '1111';
    // $data['photos']=array('https://hjwdds-app.wdds.me/201805/5afe7902b7c1c.png','https://hjwdds-app.wdds.me/201805/5afe7903bc373.png');
    // $data['specs'] = array(array('name'=>1,'price'=>2,'stock'=>3),array('name'=>1,'price'=>2,'stock'=>3));
    // $data['is_not_return'] = '11111';
    // $data['content'] = '11111';
    // $data['start_time'] = '11111';
    // $data['end_time'] = '11111'; 
    // $data['buy_max'] = '11111';
    // $data['buy_limit'] = '11111';
    // $this->shop_id = 46;

    $default_data = array(
      'shop_id' => $this->shop_id,
      'title' => '',
      'created_at' => $this->current_time,
      'updated_at' => $this->current_time);
    $data = array_merge($default_data, $data);

    !$data['logo'] && $data['logo'] = 'http://wdds-app.b0.upaiyun.com/default/logo.jpg';


    $model = M($this->this_table);

     //验证合法性
    if (!$data['name'] || !$data['logo'] || !$data['price'] || !$data['product_num'] || !$data['end_time'] || !$data['start_time']){
      return_data("error", $this->this_table.".info.empty",$data);
    }

    //商品数量限制
    $product_cates_count = $model->where("shop_id={$this->shop_id} and status=1")->count();
    $product_cates_limit = M('shops')->where("id={$this->shop_id}")->getField('product_cates_limit');
    if ($product_cates_limit != 0 && $product_cates_count >= $product_cates_limit) {
      return_data("error", "product_cates.num.limit", $product_cates_limit);
    }

    //商品重名检查
    $product_id = $model->where("shop_id={$this->shop_id} and name='{$data[name]}' and status < 2")->getField('id');
    if ($product_id) {
      return_data("error", $this->this_table.".name.exist");
    }

    $model->create($data);
    $id = $model->add();
    if (empty($id)) {
      return_data("error", "create.".$this->this_table.".error");  //blank
    } else {
      //规格新增 specs
      $specs = $data['specs'];
      if ($specs) {
        $len = 0;
        $prices = array();
        foreach ($specs as $key => $value) {
          if ($value['name']) {
            $specs_list[$len]['name'] = $value['name'];
            $specs_list[$len]['price'] = $value['price'];
            $specs_list[$len]['stock'] = $value['stock'];
            $specs_list[$len]['product_id'] = $id;
            $specs_list[$len]['created_at'] = $this->current_time;
            $len++;
            array_push($prices, $value['price']);
          }
        }
        if ($len > 0) {
          M("specs")->addAll($specs_list);
        }

        //商品表price存储spec最低价格，修改时同步；
        if ($prices) {
          $index = array_search(min($prices), $prices);
          M("products")->where("id=$id")->save(array('price' => $prices[$index]));
        }
      }

      if ($data['photos']) {
        $photo_list = [];
        foreach ($data['photos'] as $photo) {
          $photo_list[] = ['image' => $photo, 'photoable_type' => 'MsProduct', 'photoable_id' => $id];
        }
        M('photos')->addAll($photo_list);
      }

      $miaosha = M('miaosha_products');
      $form['is_delete'] = 0;
      $form['buy_max'] =  I("buy_max", 0);
      $form['buy_limit'] =  I("buy_limit", 0);
      $form['goods_id'] = $id;
      $form['start_time'] = $data['start_time'];
      $form['order_id'] = I("order_id", 0);
      $form['end_time'] = $data['end_time'];

      $miaosha->create($form);
      $ids = $miaosha->add();
      if (empty($ids)) {
        return_data("error", "create.miaosha_products.error");  //blank
      }else{
        return_data("success", "create.miaosha_products.success", $id);
      }
    }
  }
  /**
   * [商品信息]
   * @return [type] [description]
   */
  public function show()
  {
    $id = trim(I('id'));
    if (!$id) {
      return_data("error", "id.".$this->this_table.".empty");
    }
    //status状态,0:下架；1：上架 ；2：假删除
    //普通用户不看删除和已下架，商户可看
    $where = "ms.id=$id and ms.is_delete=0";
    if (I("is_business",true)) {
      $where .= " and p.status=1";
    } else {
      $this->shops_close();
      $where .= " and p.status in(0,1)";
    }
    $model = M('miaosha_products');
    $field = "ms.id as mid,p.id,p.original_price,p.product_num,p.logo,p.pf_id,p.name,p.price,p.status,ms.start_time,ms.end_time,ms.buy_max,ms.buy_limit";
    $list = $model->alias("ms")->field($field)->where($where)->join("left join ".C('DB_PREFIX')."products p on p.id=ms.goods_id")->find();
    //$list['content'] = str_replace(array("\r\n"), "\n", $list['content']);
    if(!$list['id']){
      return_data("error", "miaosha.empty");
    }

    $specs = M('specs')->field('id,price, name,stock')->where("product_id=$list[id]")->select();
    $list['specs'] = $specs;

    if($info['pf_id'] > 0){
      $photos_where = ['photoable_id' => $list['pf_id']];
    } else {
      $photos_where = ['photoable_id' => $list['id']];
    }

    $photo_result = M('photos')->field('image')->where($photos_where)->select();
    $photo_list = [];
    if ($photo_result) {
        foreach ($photo_result as $result) {
          $photo_list[] = $result['image'];
        }
    }

    $list['photos'] = $photo_list;
    if($list){
      return_data("success", "show.".$this->this_table.".success", $list);
    } else {
      return_data("error", "show.".$this->this_table.".empty", $list);
    }
  }

  /**
   * [秒杀商品列表]
   * @return [type] [description]
   */
  public function index()
  {
    $model = M($this->this_table);

    $page_index = I("page_index", 1);
    $page_size = I("page_size", 50);
    $shop_id = I('shop_id');

    //秒杀列表
     if(!$shop_id){
      return_data("error","shop_id.".$this->this_table.".empty");
    }
      $where = "ms.is_delete=0";
      if (I("is_business",true)) {
        $where .= " and p.shop_id=$shop_id and p.status=1";
      } else {
        $where .= " and p.shop_id=$shop_id and p.status in(0,1)";
        $this->shops_close();
      }

    //排序
    $order = "ms.order_id ASC,ms.id desc";
    $field = "ms.id as mid,p.id,p.original_price,p.product_num,p.logo,p.name,p.price,p.status,ms.start_time,ms.end_time,ms.buy_max,ms.buy_limit";
    $list = $model->alias("p")->join("left join ".C('DB_PREFIX')."miaosha_products ms on p.id=ms.goods_id")->field($field)->where($where)->order($order)->page($page_index.",".$page_size)->select();

      if ($list) {
        foreach ($list as $key => &$value) {
          // $specs = M('specs')->field('price, name,stock')->where("product_id=$value[id]")->select();
          // $value['specs'] = $specs;
          $value['logo'] = "{$value['logo']}!315x315";
          $value['name'] = sub_str($value['name'], 20);
        }
        return_data("success", "index.".$this->this_table.".success", $list);
      } else {
        return_data("error", "index.".$this->this_table.".empty");
      }
    
  }

  /**
   * [修改商品]
   * @return [type] [description]
   */
  public function update()
  {
    $model = M($this->this_table);

    $payload = file_get_contents('php://input');
    $data = json_decode($payload, true);
    $data['updated_at'] = $this->current_time;

    unset($data['shop_id']);
    unset($data['created_at']);
    // $this->shop_id = 46;
    // $data = [];
    // $data['id'] = 3;
    // $data['name'] = '1114311';
    // $data['logo'] = '1111';
    // $data['price'] = '1111111';
    // $data['product_num'] = '1111';
    // $data['original_price'] = '1111';
    // $data['photos']=array('https://hjwdds-app.wdds.me/201805/5afe7902b7c1c.png','https://hjwdds-app.wdds.me/201805/5afe7903bc373.png');
    // $data['specs'] = array(array('name'=>1,'price'=>2,'stock'=>3),array('name'=>1,'price'=>2,'stock'=>3));
    // $data['is_not_return'] = '11111';
    // $data['content'] = '11111';
    // $data['start_time'] = '111111';
    // $data['end_time'] = '11111';
    // $data['order_id'] = '124';
    // $data['buy_max'] = '11111';
    // $data['buy_limit'] = '111411';

    // 根据后期变化
    $data['id'] = (int)M('miaosha_products')->field('goods_id')->where("id = ".$data['id'])->find()['goods_id'];


      //验证合法性
      if (!$data['id'] || !$data['name'] || !$data['price'] || !$data['product_num'] || !$data['end_time'] || !$data['start_time']){
        return_data("error", $this->this_table.".info.empty");
      }

      $form = [];
      $form['name'] = $data['name'];
      $form['logo'] = $data['logo'];
      $form['price'] = $data['price'];
      $form['updated_at'] = $this->current_time;
      $form['product_num'] = $data['product_num'];
      $form['content'] = $data['content'];
      $form['is_not_return'] = I("is_not_return");
      $form['original_price'] = $data['original_price'];

      $model->create($form);
      $map = array('id' => $data['id'],'shop_id' => $this->shop_id);

      if($model->where($map)->save($form)){
        //商品表price存储spec最低价格，修改时同步；
          if ($data['specs']) {
            $len = 0;
            $prices = array();

            foreach ($data['specs'] as $key => $value) {
              if ($value['name']) {
                $specs_list[$len]['name'] = $value['name'];
                $specs_list[$len]['price'] = $value['price'];
                $specs_list[$len]['stock'] = $value['stock'];
                $specs_list[$len]['product_id'] = $data['id'];
                $specs_list[$len]['updated_at'] = $this->current_time;
                $specs_list[$len]['created_at'] = $this->current_time;
                $len++;

                array_push($prices, $value['price']);
              }
            }
            if ($len > 0) {
              M("specs")->where("product_id={$data[id]}")->delete();
              M("specs")->addAll($specs_list);
            }

            if ($prices) {
              $index = array_search(min($prices), $prices);
              M("products")->where("id=$data[id]")->save(array('price' => $prices[$index]));
            }
        }else{
            M("specs")->where("product_id={$data[id]}")->delete();
        }

      //图片修改
      if ($data['photos']) {
        M('photos')->where(['photoable_type' => 'MsProduct', 'photoable_id' => $data['id']])->delete();
        $photo_list = [];
        foreach ($data['photos'] as $photo) {
          $photo_list[] = ['image' => $photo, 'photoable_type' => 'MsProduct', 'photoable_id' => $data['id']];
        }
        $photo_model = M('photos');
        $photo_model->addAll($photo_list);
      } else {
        $count = M('photos')->where("photoable_id={$data['id']}")->count();
        if ($count) {
          M('photos')->where("photoable_id={$data['id']}")->delete();
        }
      }

      //秒杀修改
      $miaosha = M("miaosha_products");
      $form=[];
      $form['start_time'] = $data['start_time'];
      $form['end_time'] = $data['end_time'];
      $form['buy_max'] = I("buy_max", 0);
      $form['attr'] = time(); // 暂定 ////无意义
      $form['buy_limit'] = I("buy_limit", 0);
      $form['order_id'] = $data['order_id'];

      $miaosha->create($form);
      $map = array('goods_id' => $data['id']);
      $result = $miaosha->where($map)->save($form);
      if($result){
        return_data("success", "update.".$this->this_table.".success");        
      }
    }
    return_data("error", "update.".$this->this_table.".error");
    

  }

  /*
   * 秒杀商品删除
   */
  public function delete(){
    $model = M('miaosha_products');
    $id = I("id");
    if (!$id) {
      return_data("error", "id.".$this->this_table.".empty");
    }
    $model->where("id = $id")->save(array('is_delete'=>1));
    return_data("success", "delete.".$this->this_table.".success");
  }
}